package com.alibaba.zihao.service.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.logging.Logger;

/**
 * Created by jason on 3/9/15.
 */
public class SimpleDataSource implements javax.sql.DataSource {

    private static Connection cnn = null;

    private final String url = "jdbc:mysql://localhost:3306/dzh_mysql";

    private final String userName = "zihao";

    private final String passWord = "haozi";

    private static LinkedList<Connection> pool = (LinkedList<Connection>) Collections.synchronizedList(new LinkedList<Connection>());

    private static SimpleDataSource instance = new SimpleDataSource();

    private SimpleDataSource(){}

    public SimpleDataSource getInstance(){

        if (instance ==null)instance = new SimpleDataSource();
        return instance;
    }

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("找不到驱动类！");
        }
    }

    public Connection getConnection() {
        synchronized (pool) {
            if (pool.size() > 0) return pool.removeFirst();

            try {
                cnn = DriverManager.getConnection(url, userName, passWord);
            } catch (SQLException e) {
                System.out.println("连接失败！");
            }
            return cnn;
        }
    }

    public void freeConnection(Connection cn){
        pool.addLast(cn);
    }

    public java.io.PrintWriter getLogWriter() throws SQLException{return null;}

    public void setLogWriter(java.io.PrintWriter out) throws SQLException{}

    public void setLoginTimeout(int seconds) throws SQLException{}

    public int getLoginTimeout() throws SQLException{return 0;}

    public Logger getParentLogger() throws SQLFeatureNotSupportedException{return null;}

    public Connection getConnection(String username, String password)
            throws SQLException{return null;}
    public <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException{return null;}

    public boolean isWrapperFor(java.lang.Class<?> iface) throws java.sql.SQLException{return false;}



}
